import 'package:flutter/material.dart';
import 'package:happy_elf_app/utils/adaption.dart';
import 'package:happy_elf_app/utils/color.dart';

class ShadowedRectangularTrackShape extends SliderTrackShape {
  final double shadowBlur;
  final Color shadowColor;

  const ShadowedRectangularTrackShape({
    this.shadowBlur = 3.0,
    this.shadowColor = const Color.fromRGBO(0, 0, 0, 0.1),
  });

  @override
  Rect getPreferredRect({
    required RenderBox parentBox,
    Offset offset = Offset.zero,
    required SliderThemeData sliderTheme,
    bool isEnabled = false,
    bool isDiscrete = false,
  }) {
    // 计算轨道尺寸（高度10px，宽度占满父容器）
    final trackHeight = sliderTheme.trackHeight ?? 10.0;
    final trackLeft = offset.dx;
    final trackTop = offset.dy + (parentBox.size.height - trackHeight) / 2;
    final trackWidth = parentBox.size.width;
    return Rect.fromLTWH(trackLeft, trackTop, trackWidth, trackHeight);
  }

  @override
  void paint(
    PaintingContext context,
    Offset offset, {
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    required Animation<double> enableAnimation,
    required TextDirection textDirection,
    required Offset thumbCenter,
    Offset? secondaryOffset,
    bool isDiscrete = false,
    bool isEnabled = false,
  }) {
    final canvas = context.canvas;
    final trackRect = getPreferredRect(
      parentBox: parentBox,
      offset: offset,
      sliderTheme: sliderTheme,
      isEnabled: isEnabled,
      isDiscrete: isDiscrete,
    );
    final shadowPaint = Paint()
      ..color = shadowColor
      ..maskFilter = MaskFilter.blur(BlurStyle.normal, shadowBlur);
    canvas.drawRRect(
      RRect.fromRectAndRadius(trackRect, Radius.circular(2)),
      shadowPaint,
    );

    // 2. 绘制轨道背景（白色）
    final inactivePaint = Paint()..color = sliderTheme.inactiveTrackColor!;
    canvas.drawRRect(
      RRect.fromRectAndRadius(trackRect, Radius.circular(2)),
      inactivePaint,
    );

    final activeRect = Rect.fromLTWH(
      trackRect.left,
      trackRect.top,
      thumbCenter.dx - trackRect.left, // 激活部分宽度随滑块位置变化
      trackRect.height,
    );
    final activePaint = Paint()..color = sliderTheme.activeTrackColor!;
    canvas.drawRRect(
      RRect.fromRectAndRadius(activeRect, Radius.circular(2)),
      activePaint,
    );
  }
}

class CustomRectangularThumbShape extends SliderComponentShape {
  final double width;
  final double height;
  final double shadowBlur;
  final Color shadowColor;

  const CustomRectangularThumbShape({
    this.width = 12.0,
    this.height = 26.0,
    this.shadowBlur = 4.0,
    this.shadowColor = const Color.fromRGBO(0, 0, 0, 0.2),
  });

  @override
  Size getPreferredSize(bool isEnabled, bool isDiscrete) {
    return Size(width, height + shadowBlur);
  }

  @override
  void paint(
    PaintingContext context,
    Offset center, {
    required Animation<double> activationAnimation,
    required Animation<double> enableAnimation,
    required bool isDiscrete,
    required TextPainter labelPainter,
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    required TextDirection textDirection,
    required double value,
    required double textScaleFactor,
    required Size sizeWithOverflow,
  }) {
    final canvas = context.canvas;
    final rect = Rect.fromCenter(
      center: center,
      width: width,
      height: height,
    );

    // 绘制滑块阴影
    final shadowPaint = Paint()
      ..color = shadowColor
      ..maskFilter = MaskFilter.blur(BlurStyle.normal, shadowBlur);
    canvas.drawRect(rect.shift(Offset(0, 2)), shadowPaint);

    // 绘制滑块本体
    final thumbPaint = Paint()..color = sliderTheme.thumbColor!;
    canvas.drawRect(rect, thumbPaint);
  }
}

class moodModel {
  static late Function success; // 回掉
  static dynamic buildContext;
  static bool isModel = false;
  static Function? setModalState; // 更新

  static List completeList = [
    {'text': '开心', 'num': 1},
    {'text': '喜悦', 'num': 1},
    {'text': '兴奋', 'num': 1},
    {'text': '满足', 'num': 1},
    {'text': '狂喜', 'num': 1},
    {'text': '得意', 'num': 1},
    {'text': '自豪', 'num': 1},
    {'text': '乐观', 'num': 1},
    {'text': '难过', 'num': -1},
    {'text': '烦躁', 'num': -1},
    {'text': '沮丧', 'num': -1},
    {'text': '担忧', 'num': -1},
    {'text': '害怕', 'num': -1},
    {'text': '孤独', 'num': -1},
    {'text': '恼怒', 'num': -1},
    {'text': '忐忑', 'num': -1},
  ];

  static String check = ''; // 选中的心情

  static init({required Function callBack, required context}) {
    success = callBack;
    buildContext = context;
    isModel = false;
    print('z走到这里了');

    model(buildContext);
  }

  static Widget checkItem(e) {
    print('checkList$check');
    return GestureDetector(
      child: Container(
        width: 100.px,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: check == e['text'] ? hexColor('#e9614d') : Colors.white,
          border: Border.all(
              width: 1.px,
              color: hexColor('#b1b1b1'),
              style: BorderStyle.solid),
          // 定义虚线的线段长度和间隔（数组元素依次为：线段长度、间隔长度）
          borderRadius: BorderRadius.circular(12), // 可选：圆角
        ),
        child: Text(
          e['text'],
          style: TextStyle(
              color: check == e['text']
                  ? hexColor('#ffffff')
                  : hexColor('#484848')),
        ),
      ),
      onTap: () {
        setModalState!(() {
          check = e['text'];
        });
      },
    );
  }

  static model(buildContext) {
    if (isModel) return;
    isModel = true;
    double _sliderValue = 4.0; // 初始值设为4

    // 根据滑块值获取对应的颜色
    Color _getSliderColor(double value) {
      if (value > 4) {
        return hexColor('#e9614d');
      } else if (value == 4) {
        return hexColor('#FFB4A9');
      } else {
        return hexColor('#D2D2D2');
      }
    }

    showDialog(
        barrierDismissible: false, // 禁用点击空白处关闭对话框
        context: buildContext,
        builder: (BuildContext context) {
          return StatefulBuilder(builder: (context, setSelfState) {
            setModalState = setSelfState;
            return UnconstrainedBox(
                child: ClipRRect(
              borderRadius: BorderRadius.circular(20.px),
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                width: 300,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20.px),
                ),
                child: Column(
                  children: [
                    const Text('请选择您完成任务后的心情',
                        style: TextStyle(fontWeight: FontWeight.w500)),
                    SliderTheme(
                      data: SliderThemeData(
                        trackHeight: 16.0, // 轨道高度10px
                        activeTrackColor:
                            _getSliderColor(_sliderValue), // 激活部分颜色
                        inactiveTrackColor: Colors.white, // 底色白色
                        // 隐藏刻度节点
                        activeTickMarkColor: Colors.transparent,
                        inactiveTickMarkColor: Colors.transparent,
                        thumbColor: Colors.white,
                        // 使用带阴影的自定义滑块
                        thumbShape: CustomRectangularThumbShape(
                          width: 12.0,
                          height: 26.0,
                        ),
                        // 使用带阴影的轨道
                        trackShape: const ShadowedRectangularTrackShape(),
                        overlayColor: Colors.transparent, // 去掉点击光晕
                        showValueIndicator: ShowValueIndicator.never, // 不显示标签
                      ),
                      child: Slider(
                        value: _sliderValue,
                        min: 0,
                        max: 7,
                        divisions: 7,
                        label: null,
                        onChanged: (double value) {
                          setModalState!(() {
                            _sliderValue = value;
                          });
                          print('当前进度：$_sliderValue');
                        },
                      ),
                    ),
                    SizedBox(height: 24.px),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Image.asset(
                          'lib/assets/images/home/genertate/sad.png',
                          width: 30,
                          height: 30,
                        ),
                        Image.asset(
                          'lib/assets/images/home/genertate/happy.png',
                          width: 30,
                          height: 30,
                        )
                      ],
                    ),
                    SizedBox(height: 24.px),
                    Wrap(
                      spacing: 12,
                      runSpacing: 10,
                      children: [...completeList.map((e) => checkItem(e))],
                    ),
                    SizedBox(height: 24),
                    GestureDetector(
                      child: Container(
                        padding: EdgeInsets.symmetric(
                            horizontal: 30.px, vertical: 8.px),
                        decoration: BoxDecoration(
                            color: hexColor('#e9614d'),
                            borderRadius: BorderRadius.circular(10.px)),
                        child: Text(
                          '确定',
                          style: TextStyle(
                              fontSize: 14, color: hexColor('#ffffff')),
                        ),
                      ),
                      onTap: () {
                        check = '';
                        success(check, _sliderValue);
                      },
                    )
                  ],
                ),
              ),
            ));
          });
        });
  }
}
